import read_tsp as rt
import nearest_neighbor as nn
import write_file as wf
import farthest_insertion as fi
import nearest_insertion as ni
import cv2
import numpy as np
from sys import *
import time
import math

#输入格式示例：python main.py scenery1.2000.tsp nn

def main():
    #记录开始时间
    timestart = time.time()

    #读取tsp文件
    cities = rt.read_tsp_file('.\data\%s'%argv[1])

    #选择算法
    if argv[2] == 'nn':
        path,path_number = nn.nearest_neighbor_tsp(cities)
    elif argv[2] == 'fi':
        path,path_number = fi.Farthest_insertion(cities)
    elif argv[2] == 'ni':
        path,path_number = ni.Nearest_insertion(cities)
    else: 
        print("仅限输入ni(最近插入)nn(最近邻)fi(最远插入)")
        return 
    
    #绘制连线并计算路径长度
    path_length = 0
    img = np.ones((480, 640, 3), dtype=np.uint8) * 255
    for i in range(len(path)-1):
        cv2.line(img,(path[i][0],path[i][1]),(path[i+1][0],path[i+1][1]),(0,0,0))
        path_length += math.sqrt((path[i][0]-path[i+1][0])**2 + (path[i][1]-path[i+1][1])**2)
    print("路径长度:%f"%path_length)

    #保存路径文件
    wf.write_path_file(path_number,argv[2],path_length)

    # 记录最后时间
    timeend = time.time()
    print("时间:%s"%(timeend - timestart))

    # 在图像上写字
    time_text = 'time:' + str(round((timeend - timestart), 2)) + 's'
    len_text = 'length:' + str(round(path_length,2)) + 'm'
    font = cv2.FONT_HERSHEY_SIMPLEX
    time_position = (50, 430)
    len_position = (50, 460)
    font_scale = 1
    color = (0, 0, 0)
    thickness = 1  
    cv2.putText(img, time_text, time_position, font, font_scale, color, thickness)
    cv2.putText(img, len_text, len_position, font, font_scale, color, thickness)
    cv2.putText(img, argv[1][-8:-4], (500,430), font, font_scale, color, thickness)

    #显示图像
    cv2.imshow(argv[1][:-4], img) 

    #保存图像
    img_name = argv[1][:-4] + argv[2]
    cv2.imwrite('.\image\\' + img_name + '.jpg', img)

    #输入任意键结束
    cv2.waitKey(0)
    cv2.destroyAllWindows()
   
if __name__ == "__main__":
    main()
